package com.realbrand.net.realbrandpay.ui.activity.login;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.realbrand.net.realbrandpay.APP;
import com.realbrand.net.realbrandpay.R;
import com.realbrand.net.realbrandpay.base.BaseActivity;
import com.realbrand.net.realbrandpay.inter.IPhoneCodeLogin;
import com.realbrand.net.realbrandpay.inter.IPhoneLogin;
import com.realbrand.net.realbrandpay.ui.activity.shopcar.CheckOutActivity;
import com.realbrand.net.realbrandpay.ui.activity.wallet.WalletActivity;
import com.realbrand.net.realbrandpay.api.HTTPAPI;
import com.realbrand.net.realbrandpay.untils.Static;
import com.realbrand.net.realbrandpay.zxing.util.L;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

/**
 * Created by Administrator on 2017/6/20.
 */

public class PhoneLoginActivity extends BaseActivity {
    @BindView(R.id.phonelogin_et_phone)
    EditText phoneloginEtPhone;
    @BindView(R.id.phonelogin_iv_clean)
    ImageView phoneloginIvClean;
    @BindView(R.id.phonelogin_et_phoneCode)
    EditText phoneloginEtPhoneCode;
    @BindView(R.id.phonelogin_bt_sendPhoneCode)
    Button phoneloginBtSendPhoneCode;
    @BindView(R.id.phonelogin_tv_regist)
    TextView phoneloginTvRegist;
    @BindView(R.id.phonelogin_tv_passwordLogin)
    TextView phoneloginTvPasswordLogin;
    @BindView(R.id.phonelogin_bt_login)
    Button phoneloginBtLogin;
    //请求获取的验证码
    private String phoneCode;
    //用户输入的手机号
    private String phone;
    //用户输入的验证码
    private String phoneCodeByUser;
    //定时器
    private TimeCount time;

    @Override
    protected int getLayoutId() {
        return R.layout.phonelogin_activity;
    }

    @Override
    protected void setOnClick() {
        phoneloginIvClean.setOnClickListener(this);
        phoneloginBtSendPhoneCode.setOnClickListener(this);
        phoneloginTvRegist.setOnClickListener(this);
        phoneloginTvPasswordLogin.setOnClickListener(this);
        phoneloginBtLogin.setOnClickListener(this);

    }


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getLayoutId());
        ButterKnife.bind(this);
        time = new TimeCount(120000, 1000);
        setOnClick();

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            //点击清除手机号
            case R.id.phonelogin_iv_clean:
                phoneloginEtPhone.setText("");
                break;
            //点击发送验证码
            case R.id.phonelogin_bt_sendPhoneCode:
                phone = phoneloginEtPhone.getText().toString();
                phoneloginBtSendPhoneCode.setClickable(false);
                if (!TextUtils.isEmpty(phone)) {
                    if (Static.isMobileNO(phone)) {
                        JSONObject object = new JSONObject();
                        try {
                            object.put("METHOD", "GetAuthCode");
                            object.put("SOURCE", "PhoneLoginActivity");
                            object.put("CREDENTIALS", "0");
                            object.put("TERMINAL", "1");
                            object.put("INDEX", Static.getDay());
                            object.put("UserMobile", phone);
                            getPhoneCode(object.toString());
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    } else {
                        Toast.makeText(this, "请输入正确的手机号码", Toast.LENGTH_LONG).show();
                    }
                } else {
                    Toast.makeText(this, "请输入手机号码", Toast.LENGTH_LONG).show();
                }
                break;
            //点击注册
            case R.id.phonelogin_tv_regist:
                startActivity(new Intent(this, RegistActivity.class));
                finish();
                break;
            //点击密码登录
            case R.id.phonelogin_tv_passwordLogin:
                startActivity(new Intent(this, LoginActivity.class));
                finish();
                break;
            //点击登录
            case R.id.phonelogin_bt_login:
                phoneCodeByUser = phoneloginEtPhoneCode.getText().toString();
                phone = phoneloginEtPhone.getText().toString();
                if (TextUtils.isEmpty(phone)) {
                    Static.toast(this, "请输入手机号");
                } else {
                    if (Static.isMobileNO(phone)) {
                        if (TextUtils.isEmpty(phoneCodeByUser)) {
                            Static.toast(this, "请输入验证码");
                        } else {
                            login();
                        }
                    } else {
                        Static.toast(this, "请输入正确的手机号");
                    }
                }
                Log.d("zhu", "用户输入的验证码" + phoneCodeByUser);
                break;
        }

    }

    private void login() {
        try {
            final JSONObject jsonObject = new JSONObject();
            jsonObject.put("METHOD", "MobileLogin");
            jsonObject.put("SOURCE", "PhoneLoginActivity");
            jsonObject.put("CREDENTIALS", "0");
            jsonObject.put("TERMINAL", "1");
            jsonObject.put("INDEX", Static.getDay());
            jsonObject.put("UserMobile", phone);
            jsonObject.put("Verification", phoneCodeByUser);
            RequestBody body = RequestBody.create(HTTPAPI.JSON, jsonObject.toString());
            Retrofit retrofit = new Retrofit.Builder().baseUrl(HTTPAPI.BASE_URL).build();
            IPhoneCodeLogin iPhoneCodeLogin = retrofit.create(IPhoneCodeLogin.class);
            Call<ResponseBody> call = iPhoneCodeLogin.phoneCode(body);
            call.enqueue(new Callback<ResponseBody>() {
                @Override
                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                    //拿到返回结果
                    try {
                        String reault = response.body().string();
                        Log.d("zhu", "返回结果：" + reault);
                        try {
                            JSONObject object = new JSONObject(reault);
                            String credentials = object.getString("CREDENTIALS");
                            JSONArray data = object.getJSONArray("DATA");
                            JSONObject json = data.getJSONObject(0);
                            String s = json.getString("result");
                            Log.d("zhu", "请求结果：" + s);
                            if ("登录失败！".equals(s)) {
                                Intent intent = new Intent(new Intent(PhoneLoginActivity.this, DatumActivity.class));
                                intent.putExtra("UserPhone", phone);
                                startActivity(intent);
                                finish();
                            } else if ("登录成功！".equals(s)) {
                                //表示登录成功，然后跳转界面
                                Log.d("zhu", "执行跳转");
                                //用户已授权的数据
                                JSONArray bankName = json.getJSONArray("BankName");
                                JSONArray payAccount = json.getJSONArray("PayAccount");
                                JSONArray name = json.getJSONArray("UserName");
                                SharedPreferences preferences = getSharedPreferences("userMassage", MODE_PRIVATE);
                                SharedPreferences.Editor editor = preferences.edit();
                                if (bankName.length() != 0) {
                                    for (int i = 0; i < bankName.length(); i++) {
                                        if (bankName.getString(i).equals("微信")) {
                                            APP.WXIsAuth = true;
                                            String WXAccount = payAccount.getString(i);
                                            String WXName = name.getString(i);
                                            editor.putString("WX", WXAccount);
                                            editor.putString("WXName", WXName);
                                            editor.commit();
                                        } else if (bankName.getString(i).equals("支付宝")) {
                                            APP.AlipayIsAuth = true;
                                            String alipayAccount = payAccount.getString(i);
                                            String alipayName = name.getString(i);
                                            editor.putString("alipay", alipayAccount);
                                            editor.putString("alipayName", alipayName);
                                            editor.commit();
                                        }
//                                        } else if (bankName.getString(i).equals("龙支付")) {
//                                            LoginActivity.JianHangIsAuth = true;
//                                            String jianHangAccount = payAccount.getString(i);
//                                            String jianHangName = name.getString(i);
//                                            editor.putString("jianhang", jianHangAccount);
//                                            editor.putString("jianhangName", jianHangName);
//                                            editor.commit();
//                                        }
                                    }
                                }

                                String account = json.getString("UserAccount");
                                String mobile = json.getString("UserMobile");
                                String balance = json.getString("UserBalance");
                                String avatar = json.getString("UserAvatar");
                                String addresseeName = json.getString("AddresseeName");
                                String telephone = json.getString("Telephone");
                                String province = json.getString("Province");
                                String regionCity = json.getString("RegionCity");
                                String countyDistrict = json.getString("CountyDistrict");
                                String detailedAddress = json.getString("DetailedAddress");
                                String strCode = json.getString("Code");
                                String userType = json.getString("UserType");
                                //获取当前时间戳
                                long time = Static.timeNow();
                                //存储用户信息
                                Static.saveMassage(PhoneLoginActivity.this, account, mobile, balance, avatar, addresseeName, telephone,
                                        province, regionCity, countyDistrict, detailedAddress, strCode, userType, credentials, time);
                                //登录成功，如果是从购物车界面过来就跳转到结算界面，其他就跳转到钱包界面
                                LoginActivity.isLogin = true;
                                if (LoginActivity.isFormShopCar) {
                                    finish();
                                } else if (LoginActivity.isFormPick) {
                                    finish();
                                } else {
                                    startActivity(new Intent(PhoneLoginActivity.this, WalletActivity.class));
                                    finish();
                                }
                            } else if ("验证码已过时".equals(s)) {
                                Static.toast(PhoneLoginActivity.this, "验证码超时");
                            } else if ("验证码错误".equals(s)) {
                                Static.toast(PhoneLoginActivity.this, "验证码错误");
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                        L.d(L.TAG, "登录异常" + e.toString());
                    }
                }

                @Override
                public void onFailure(Call<ResponseBody> call, Throwable t) {

                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    //请求验证码
    private void getPhoneCode(String json) {

        RequestBody body = RequestBody.create(HTTPAPI.JSON, json);
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(HTTPAPI.BASE_URL)
                .build();
        IPhoneLogin getCode = retrofit.create(IPhoneLogin.class);
        Call<ResponseBody> call = getCode.phoneLogin(body);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                if (response == null) {
                    Static.toast(PhoneLoginActivity.this, "网络繁忙");
                } else {
                    try {
                        String reault = response.body().string();
                        //验证码
                        phoneCode = new JSONObject(reault).getString("Verification");
                        Log.d("zhu", "收到的验证码" + phoneCode);
                        time.start();
                    } catch (Exception e) {
                        e.printStackTrace();
                        phoneloginBtSendPhoneCode.setClickable(true);
                    }
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                phoneloginBtSendPhoneCode.setClickable(true);
            }
        });
    }

    class TimeCount extends CountDownTimer {

        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            phoneloginBtSendPhoneCode.setBackground(getResources().getDrawable(R.drawable.bt_regist));
            phoneloginBtSendPhoneCode.setClickable(false);
            phoneloginBtSendPhoneCode.setText(millisUntilFinished / 1000 + "s后可重发");
        }

        @Override
        public void onFinish() {
            phoneloginBtSendPhoneCode.setText("重新获取验证码");
            phoneloginBtSendPhoneCode.setClickable(true);
            phoneloginBtSendPhoneCode.setBackground(getResources().getDrawable(R.drawable.bt_regist));
        }
    }


}
